# -*- coding: utf-8 -*-
"""
Coroutines and concurrency/Tornado Gen/test01.py
"""
import time
import asyncio
import tornado.web
import random
from tornado import gen
from tornado.httpclient import AsyncHTTPClient


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        """
        异步, call back形式
        :return:
        """
        http_client = AsyncHTTPClient()
        response = http_client.fetch("http://www.baidu.com/")
        response.add_done_callback(self.on_response)
        self.finish("I'm back.")

    def on_response(self, result):
        print(result)

    def post(self):
        """
        异步, gen yield
        :return:
        """
        response = self.other_func()
        print(response)
        self.write("I'm back.")

    @gen.coroutine
    def other_func(self):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch("http://www.baidu.com/")
        return response

    def put(self):
        """
        异步, gen yield return
        :return:
        """
        urls = ["http://www.baidu.com", "http://www.google.com"]
        [self.put_process(url) for url in urls]
        self.finish("I'm back.")

    @gen.coroutine
    def put_process(self, url):
        task_id = random.randint(0, 5)
        print(f"Task id {task_id} start. {time.time()}")
        response = yield self.put_task(url)
        print(response)
        print(f"Task id {task_id} end. {time.time()}")

    @gen.coroutine
    def put_task(self, url):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(url)
        raise gen.Return(response)


async def main():
    app = tornado.web.Application([
        (r"/", IndexHandler)
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())
